package com.bsg.upm.service;

import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.http.HttpStatus;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.bsg.upm.cache.DefinitionMetricCache;
import com.bsg.upm.constant.SysConstants;
import com.bsg.upm.dao.UnitDao;
import com.bsg.upm.entity.UnitEntity;
import com.bsg.upm.exception.APIException;
import com.bsg.upm.http.RespJson;
import com.bsg.upm.http.RespJsonFactory;

/**
 * 
 * @author yucs
 *
 */
@Service
public class MonitorUnitService extends BaseService {

	@Resource
	private DefinitionMetricCache definitionMetricCache;
	@Resource
	private UnitDao unitDao;

	public RespJson historyHandle(Map<String, Object> paramMap) throws APIException {
		String unitType = (String) paramMap.get("type");
		String metric = definitionMetricCache.getMetric(unitType, (String) paramMap.get("metric"));

		if (!metric.contains(";")) {
			return getHistoryMetric(paramMap);
		}

		paramMap.put("metric", metric);
		return getBuldHistoryMetric(paramMap);
	}

	public RespJson noHistoryHandle(Map<String, Object> paramMap) throws APIException {
		String unitType = (String) paramMap.get("type");
		String metric = definitionMetricCache.getMetric(unitType, (String) paramMap.get("metric"));
		if (!metric.contains(";")) {
			return getNoHistoryMetric(paramMap);
		}

		paramMap.put("metric", metric);
		return getBuldNoHistoryMetric(paramMap);
	}

	private RespJson getBuldHistoryMetric(Map<String, Object> paramMap) throws APIException {
		String metrics = (String) paramMap.get("metric");
		List<String> metricList = Arrays.asList(metrics.split(";"));

		JSONObject jSONObject = new JSONObject();
		for (String metric : metricList) {
			Map<String, Object> newmap = new HashMap<String, Object>(paramMap);
			newmap.put("metric", metric);
			jSONObject.put(metric, getHistoryMetric(newmap).getData());
		}

		return RespJsonFactory.buildOK(jSONObject);
	}

	private RespJson getBuldNoHistoryMetric(Map<String, Object> paramMap) throws APIException {
		String metrics = (String) paramMap.get("metric");
		List<String> metricList = Arrays.asList(metrics.split(";"));

		JSONObject jSONObject = new JSONObject();
		for (String metric : metricList) {
			Map<String, Object> newmap = new HashMap<String, Object>(paramMap);
			newmap.put("metric", metric);
			jSONObject.put(metric, getNoHistoryMetric(newmap).getData());
		}

		return RespJsonFactory.buildOK(jSONObject);
	}

	public RespJson getHistoryMetric(Map<String, Object> paramMap) throws APIException {
		try {
			JSONArray retJsonArray = new JSONArray();

			UnitEntity unit = unitDao.get((String) paramMap.get("unitId"));

			if (unit == null) {
				return RespJsonFactory.buildOK(retJsonArray);
			}

			String siteId = unit.getSubServ().getServ().getOrder().getArea().getSite().getId();
			String unitId = unit.getRelateId();

			String start = (String) paramMap.get("start_time");
			String end = (String) paramMap.get("end_time");

			String unitType = (String) paramMap.get("type");
			
			String compress = "false";
		 	if (paramMap.containsKey("compress")){
				 compress = (String) paramMap.get("compress");
			}
			
			
			String metric = definitionMetricCache.getMetric(unitType, (String) paramMap.get("metric"));

			String url = String.format("/%s/units/%s?start_time=%s&end_time=%s&metric=%s&compress=%s", SysConstants.HS_VERSION,
					unitId, start, end, metric,compress);
			RespJson httpRespJson = sendHttpGet(siteId, SysConstants.INTERFACE_TYPE_HS, url);

			if (httpRespJson.getStatus() != HttpStatus.SC_OK) {
				logger.error("get horus fail:" + httpRespJson);
				throw new APIException(httpRespJson.getMsg());
			}

 
			JSONObject metrics= (JSONObject)httpRespJson.getData();
			return RespJsonFactory.buildOK(getHistoryFromcommonType(metrics));

		} catch (Exception e) {
			logger.error("getHistoryMetric fail:", e);
			throw new APIException("getHistoryMetric fail:" + e.getMessage());
		}

	}

	public RespJson getNoHistoryMetric(Map<String, Object> paramMap) throws APIException {
		try {

			JSONObject jSONObject = new JSONObject();
			UnitEntity unit = unitDao.get((String) paramMap.get("unitId"));

			if (unit == null) {
				RespJsonFactory.buildOK(jSONObject);
			}

			String siteId = unit.getSubServ().getServ().getOrder().getArea().getSite().getId();
			String unitId = unit.getRelateId();

			String unitType = (String) paramMap.get("type");
			String metric = definitionMetricCache.getMetric(unitType, (String) paramMap.get("metric"));

			long end = System.currentTimeMillis() / 1000;
			long start = end - 60 * 5;

			String url = String.format("/%s/units/%s?start_time=%d&end_time=%d&metric=%s", SysConstants.HS_VERSION,
					unitId, start, end, metric);

			RespJson httpRespJson = sendHttpGet(siteId, SysConstants.INTERFACE_TYPE_HS, url);

			if (httpRespJson.getStatus() != HttpStatus.SC_OK) {
				logger.error("get horus fail:" + httpRespJson);
				throw new APIException(httpRespJson.getMsg());
			}

	 
			JSONObject metrics= (JSONObject)httpRespJson.getData();
			return RespJsonFactory.buildOK(getNoHistoryFromcommonType(metrics));

		} catch (Exception e) {
			logger.error("getNoHistoryMetric fail:", e);
			throw new APIException("getNoHistoryMetric fail:" + e.getMessage());
		}

	}

	
}
